package org.app.config;

import org.app.interceptor.JwtInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    
    @Autowired
    private JwtInterceptor jwtInterceptor;
    
    @Value("${file.upload.path:upload}")
    private String uploadPath;
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/user/login",
                        "/user/register",
                        "/file/download/**",
                        "/upload/**",
                        "/swagger-resources/**",
                        "/webjars/**",
                        "/v2/**",
                        "/swagger-ui.html/**"
                );
    }
    
    /**
     * 配置跨域请求
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .allowedHeaders("*")
                .maxAge(3600);
    }

    /**
     * 添加资源处理器，将上传目录映射为静态资源
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 获取项目绝对路径
        File projectDir = new File("").getAbsoluteFile();
        String absoluteUploadPath = projectDir.getAbsolutePath() + File.separator + uploadPath;
        System.out.println("配置资源映射，上传路径: " + absoluteUploadPath);
        
        // 确保上传目录存在
        File uploadDir = new File(absoluteUploadPath);
        if (!uploadDir.exists()) {
            boolean created = uploadDir.mkdirs();
            System.out.println("创建上传目录: " + uploadDir.getAbsolutePath() + (created ? " 成功" : " 失败"));
        }

        // 将上传路径映射为静态资源，用于直接访问上传的文件
        registry.addResourceHandler("/upload/**")
                .addResourceLocations("file:" + absoluteUploadPath + File.separator);
                
        // 保留原有的映射以兼容旧接口
        registry.addResourceHandler("/file/download/**")
                .addResourceLocations("file:" + absoluteUploadPath + File.separator);
    }
} 